package com.zkw.group.controller;

import com.alibaba.fastjson.JSON;
import com.zkw.group.entity.ProfesTermCourse;
import com.zkw.group.entity.QueryInfo;
import com.zkw.group.service.ProfesTermCourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Api(description = "管理学期内课程信息")
@CrossOrigin
@RestController
@RequestMapping("/ProfesTermCourses")
public class ProfesTermCourseController {

    @Autowired
    private ProfesTermCourseService profesTermCourseService;

    @ApiOperation(value = "分页查询学期内课程列表")
    @GetMapping("/AllProfesTermCourse")
    public String getAllProfesTermCourseList(QueryInfo queryInfo) {
        int numbers = profesTermCourseService.getProfesTermCourseCounts(queryInfo.getQuery(),queryInfo.getRole());
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<ProfesTermCourse> profesTermCourses = profesTermCourseService.getAllProfesTermCourseList(queryInfo.getQuery(),queryInfo.getRole(),pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",profesTermCourses);
        return JSON.toJSONString(res);
    }

    @ApiOperation(value = "添加学期内课程")
    @PostMapping("/ProfesTermCourse")
    public String addProfesTermCourse(@RequestBody ProfesTermCourse profesTermCourse) {
        //得到该课程的所有先修课程列表
        String cname = profesTermCourse.getCname();
        List<String> RelacnameList = profesTermCourseService.getRelacnameList(cname);
        //得到所有该学期之前的学期的课程列表
        int ords = profesTermCourse.getOrds();
        List<String> BeforecnameList = profesTermCourseService.getBeforecnameList(ords);
        //判断前面学期的课程中是否包含该课程的先修课程
        int truenum = 0,flag = 0;
        int num = RelacnameList.size();
        for(int j = 0;j < num;j++){
            for(int i = 0;i < BeforecnameList.size();i++){
                if(RelacnameList.get(j).equals(BeforecnameList.get(i))){
                    truenum++;
                    break;
                }
            }
        }
        if(truenum == num){
            flag = 1;
        }
        if(flag != 1){
            return "courseerror";
        }
        int result =  profesTermCourseService.addProfesTermCourse(profesTermCourse);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }

    @ApiOperation(value = "删除指定学期内课程")
    @DeleteMapping("/ProfesTermCourse")
    public String deleteProfesTermCourse(String cname) {
        int result = profesTermCourseService.deleteProfesTermCourse(cname);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }
}
